package com.yangjie.autotest.component;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;

import javax.inject.Inject;
import javax.inject.Named;

import org.springframework.context.annotation.Scope;

import com.yangjie.autotest.context.ContextIF;
import com.yangjie.autotest.exception.ValidateFailedException;
import com.yangjie.log.LoggerIF;

@Named("fileValidator")
@Scope("prototype")
public class FileValidator {
	@Inject
	private LoggerIF logger = null;
	
	String basePath = null;
	
	public void init(String basePath) {
		this.basePath = basePath;
	}
	
	public void checkFileContent(ContextIF context, String fileName, String content)throws ValidateFailedException {
		int timeout = 0;
		while(timeout < 300000) {
			try {
				if(doCheckFileContent(context,fileName, content)) {
					return;
				}
			} catch(ValidateFailedException e) {
				if(timeout >= 300000) {
					throw e;
				}
				try {
					Thread.sleep(10000);
				} catch (InterruptedException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				timeout += 10000;
			}
		}
	}
	public boolean doCheckFileContent(ContextIF context, String fileName, String content)throws ValidateFailedException {
		String actualContent = "";
		content = content.replaceAll("\n", "").replaceAll("\r", "").trim();
		StringBuffer sb = new StringBuffer();
		try {
			File file = new File(basePath + File.separator + fileName);
			BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
			String line = br.readLine();
			while(line != null) {
				sb.append(line);
				line = br.readLine();
			}
			actualContent = sb.toString().trim();
			if(actualContent.equals(content)) {
				return true;
			}
			throw new ValidateFailedException("validate fileContent failed. Expected:" + content + "; actual:" + actualContent);
		} catch(Exception e) {
			e.printStackTrace();
			throw new ValidateFailedException("validate fileContent failed. Expected:" + content + "; actual:" + actualContent);
		}
	}
}
